package com.zzxy.spring3.factory;

import com.zzxy.spring3.aspect.MyAspect;
import com.zzxy.spring3.service.impl.IStudentService;
import com.zzxy.spring3.service.impl.StudentServicelmpl;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyBeanFactoryCglib {
    public static <StudentServiceimpl> IStudentService creatStudentServiceProxy() {

        StudentServiceimpl studentService = new StudentServiceimpl();

        MyAspect aspect = new MyAspect();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(studentService.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation methodInvocation) throws Throwable {
                return null;
            }

            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                aspect.before();
                Object obj = methodProxy.invokeSuper(o,objects);
                aspect.after();
                return obj;
            }
        });
        return (StudentServiceimpl)enhancer.create();
    }
}
